﻿#include "LogBox.h"

#include <QPainter>
#include <QDebug>
#include <QCoreApplication>


// 自定义事件类型
const QEvent::Type LogEvent::LogType = static_cast<QEvent::Type>(QEvent::Type::User + 1);

int LogBox::ID = 0;

LogBox::LogBox(QWidget *widget)
    : QTextEdit{widget}
    , curId(ID++)
    , dirNotifier(nullptr)
{
    this->setFrameStyle(QFrame::NoFrame);
    this->setFont(QFont("Microsoft YaHei", 10));
    this->document()->setDocumentMargin(10);

    // 应安装到viewport对象上
    viewport()->installEventFilter(this);

    HANDLE eDir = FindFirstChangeNotification(
        L"C:\\Users\\admin\\Desktop\\",
        FALSE,
        FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE
    );
    dirNotifier = new QWinEventNotifier(eDir, this);
    connect(dirNotifier, &QWinEventNotifier::activated, this, [=](HANDLE hEvent) {
        qDebug() << hEvent;
    });
}

void LogBox::paintEvent(QPaintEvent *event)
{
    QTextEdit::paintEvent(event);

    QPainter painter(viewport());
    painter.setRenderHint(QPainter::Antialiasing);

    QPen pen(Qt::gray, 1);
    painter.setPen(pen);
    QRect r = viewport()->rect();
    r.adjust(1, 1, -1, -1); // 防止边框被裁掉
    if (hasFocus()) {
        viewport()->update();
        painter.drawRoundedRect(r, 3, 3);
    }
}

bool LogBox::event(QEvent *event)
{
    if (event->type() == LogEvent::LogType) {
        LogEvent *e = static_cast<LogEvent*>(event);
        qDebug() << "Process Log Event:" << e->getMessage();
        // 或重写customEvent方法，Qt将自动将大于QEvent::User的事件转发到此函数
    }
    return QTextEdit::event(event);
}

bool LogBox::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        QCoreApplication::postEvent(this, new LogEvent("Hello world"));
        // 标记此事件已处理
        return true;
    }
    return false;
}

void LogBox::customEvent(QEvent *event)
{
    if (event->type() == LogEvent::LogType) {
        LogEvent *e = static_cast<LogEvent*>(event);
        qDebug() << "customEvent: Process Log Event:" << e->getMessage();
    }
}
